import React from 'react'
import cx from 'classnames'
import moment from 'moment'
import _ from 'underscore'
import numeral from 'numeral'

import dispatcher from 'lib/dispatcher'
import DatePicker from 'lib/components/datepicker.jsx'
import View from 'lib/View.jsx'

import { defaultApi } from '../apis/core-util';
import DateRangeStoreEnhanced from './DateRangeStoreEnhanced.es6'

class DatePicker2 extends DatePicker {
  onForward(key){
    var next = moment(this.state.value).add(1, 'month');
    if (!(this.props.limitingDateDirection === 'gt' && next.isAfter(this.props.limitingDate))) {
      this.setState(this.stateFromDate(next.valueOf(), false), this._onChange);
    }
  }

  onBackward(key){
    var last = moment(this.state.value).add(-1, 'month');
    if (!(this.props.limitingDateDirection === 'lt' && last.isBefore(this.props.limitingDate))) {
      this.setState(this.stateFromDate(last.valueOf(), false), this._onChange);
    }
  }

  isDisabled(timestamp,month,currentMonth){
    return !(timestamp >= this.props.minDate && timestamp <= this.props.maxDate) || month !== undefined && month !== currentMonth
  }

  generateMatrix(lastTimestamp) {
    let data = [];
    let current = moment(lastTimestamp).add(1, 'days');
    for (let i = 0; i < 7; i++) {
      data.push({
        date: current.date(),
        label: current.format('DD'),
        month: current.month(),
        value: current.valueOf()
      });
      current = current.add(1, 'days');
    }
    return data;
  }

  render() {
    let len = 6 - this.state.matrix.length;
    let extMatrix = [];
    let lastTimestamp = this.state.matrix[this.state.matrix.length-1][6].value;
    for (var i = 0; i < len; i++) {
      let item = this.generateMatrix(lastTimestamp);
      extMatrix.push(item);
      lastTimestamp = item[6].value;
    }
    return (
      <div className="calendar-date">
        <table className="table-condensed">
          <thead>
            <tr>
              <th>
                <i className="iconfont arrow" style={{color:'#555'}} onClick={this.state.allowBackward?this.onBackward:null}>
                  &#xe63e;
                </i>
              </th>
              <th colSpan="5">
                {this.state.year}年 {this.state.month+1}月
              </th>
              <th>
                <i className="iconfont arrow" style={{color:'#555'}} onClick={this.state.allowForward?this.onForward:null}>
                  &#xe63f;
                </i>
              </th>
            </tr>
            <tr>
              <th>日</th>
              <th>一</th>
              <th>二</th>
              <th>三</th>
              <th>四</th>
              <th>五</th>
              <th>六</th>
            </tr>
          </thead>
          <tbody>
            {
              this.state.matrix.map(function(week,n){
                return (
                  <tr key={n}>
                    {
                      week.map(function(dayObj){
                        if(this.isDisabled(dayObj.value,dayObj.month,this.state.month)){
                          return (
                            <td className="disabled" key={dayObj.date}>
                              {dayObj.label}
                            </td>
                          )
                        }else{
                          return (
                            <td onClick={this.selectDay.bind(this,dayObj.value)} className={cx({
                                active:dayObj.date === this.state.date && dayObj.month === this.state.month
                              })} key={dayObj.date}>
                              {dayObj.label}
                            </td>
                          )
                        }
                      },this)
                    }
                  </tr>
                )
              },this)
            }
            {
              extMatrix.map(function(week,n){
                return (
                  <tr key={n+this.state.matrix.length}>
                    {
                      week.map(function(dayObj){
                        return (
                          <td className="disabled" key={dayObj.date}>
                            {dayObj.label}
                          </td>
                        );
                      },this)
                    }
                  </tr>
                );
              },this)
            }
          </tbody>
        </table>
      </div>
    )
  }
}

export default class DateRangePickerEnhanced extends View {
  constructor(props) {
    super(props);

    this.toggle = this.toggle.bind(this);
    this.toggleTab = this.toggleTab.bind(this);
    this.toggleCustom = this.toggleCustom.bind(this);
    this.dayLeftChange = this.dayLeftChange.bind(this);
    this.dayRightChange =this.dayRightChange.bind(this);
    this.selectCustomItem = this.selectCustomItem.bind(this);
    this.globalCloseDisplay = this.globalCloseDisplay.bind(this);

    this.partitionApi = defaultApi({
      __url: `sd/${ BlueWare.appId }/api/partitions/list`
    });
  } // constructor

  toggle() {
    this.dispatcher.dispatch({
      $type: 'state_changed',
      data: {isOpen: !this.state.isOpen}
    });
  } // toggle

  toggleTab(isNatural) {
    this.dispatcher.dispatch({
      $type: 'state_changed',
      data: {isNatural}
    });
  } // toggleTab

  toggleCustom() {
    if (!this.state.isCustom) {
      this.dispatcher.dispatch({
        $type: 'state_changed',
        data: {isCustom: !this.state.isCustom}
      });
    }
  } // toggleCustom

  dayLeftChange(date) {
    this.dispatcher.dispatch({
      $type: 'state_changed',
      data: {rightMinDate: date, leftSelectDate: date}
    });
  }

  dayRightChange(date) {
    this.dispatcher.dispatch({
      $type: 'state_changed',
      data: {leftMaxDate: date, rightSelectDate: date}
    });
  }

  selectPredefinedItem(item, isNatural) {
    this.dispatcher.dispatch({
      $type: 'select_item',
      data: {
        isOpen: false,
        isNatural,
        isCustom: false,
        selectedItem: item
      }
    });
  } // selectPredefinedItem

  selectCustomItem() {
    let endTime = moment(this.state.rightSelectDate).valueOf();
    this.dispatcher.dispatch({
      $type: 'select_item',
      data: {
        isOpen: false,
        isCustom: true,
        selectedItem: {
          alias: null,
          text: null,
          value: {
            spanTime: endTime - this.state.leftSelectDate,
            endTime: endTime
          }
        }
      }
    });
  } // selectCustomItem

  globalCloseDisplay(e) {
    if (this.state.isOpen) {
      if(!$.contains(this.refs.root, e.target)) {
        this.dispatcher.dispatch({
          $type: 'state_changed',
          data: { isOpen: false }
        });
      }
    }
  }

  componentDidMount() {
    super.componentDidMount();

    $(document.body).on('click', this.globalCloseDisplay);

    // this.partitionApi.fetch().done(data => {
    //   let dateAvailableList = _.chain(data).sortBy(p => p);
    //   // let dateAvailableList = _.sortBy(data);
    //   // console.log('dateAvailableList', dateAvailableList);
    //   this.setState({
    //     MINDate: moment(dateAvailableList.first().value()).valueOf(),
    //     MAXDate: moment(dateAvailableList.last().value()).valueOf()
    //   });
    //   // console.log(moment(this.state.minDate)['_d']);
    //   // console.log(moment(this.state.maxDate)['_d']);
    // })
  }

  componentWillUnmount() {
    super.componentWillUnmount();

    $(document.body).off('click', this.globalCloseDisplay);
  }

  renderCustomBody() {
    return (
      <div style={{'width':'573px'}}>
      <div className="timepicker-main">

        <div key="date-picker-left" className="timepicker-diy timepicker-diy-left">
          <DatePicker2
            minDate={this.state.minDate}
            maxDate={this.state.leftMaxDate}
            defaultValue={this.state.leftSelectDate}
            limitingDateDirection={'gt'}
            limitingDate={this.state.rightSelectDate}
            onAfterChange={this.dayLeftChange} />
        </div>

        <div key="date-picker-right" className="timepicker-diy timepicker-diy-right" style={{'width':'auto'}}>
          <DatePicker2
            minDate={this.state.rightMinDate}
            maxDate={this.state.maxDate}
            defaultValue={this.state.rightSelectDate}
            limitingDateDirection={'lt'}
            limitingDate={this.state.leftSelectDate}
            onAfterChange={this.dayRightChange} />
        </div>

      </div>

      <div className="timepicker-footer">
        <span>{moment(this.state.leftSelectDate).format('YYYY-MM-DD')} 至 {moment(this.state.rightSelectDate).format('YYYY-MM-DD')}</span>
        <button onClick={this.selectCustomItem} className="btn-green" type="button">确定</button>
      </div>
    </div>
    );
  }

  renderBody() {
    return (
      <div className="mi-timepicker-dropdown-main-enhanced">
        <ul className="switch-tab-container">
          <li onClick={this.toggleTab.bind(this, true)}
              style={{ 'marginLeft': '5px' }}
              className={cx(
                {
                  'active': this.state.isNatural
                }, 'switch-tab')}>
            自然时间
          </li>
          <li onClick={this.toggleTab.bind(this, false)}
              className={cx(
                {
                  'active': !this.state.isNatural
                }, 'switch-tab')}>
            相对时间
          </li>
        </ul>
        <ul style={{'textAlign':'left', 'whiteSpace': 'nowrap'}}>
          {this.state.isNatural ?
            (
              this.state.naturalDays.map((item) => {
                return (
                  <li key={'DateRangePickerEnhanced-naturalDays-' + item.alias}
                      onClick={this.selectPredefinedItem.bind(this, item, true)}
                      className={ cx({
                        active: this.state.selectedItem.alias === item.alias
                      }) }>
                    {item.text}
                  </li>
                  )
              }, this)
            ) :
            (
              this.state.relativeDays.map((item) => {
                return (
                  <li key={'DateRangePickerEnhanced-relativeDays-' + item.alias}
                      onClick={this.selectPredefinedItem.bind(this, item, false)}
                      className={ cx({
                        active: this.state.selectedItem.alias === item.alias
                      }) }>
                    {item.text}
                  </li>
                  )
              }, this)
            )
          }
          {this.props.canHaveCustom ?
            (<li
            onClick={this.toggleCustom}
            className={cx({
              active: this.state.isCustom
            })}
            style={{'cursor': this.state.isCustom ? 'default' : 'pointer'}}>
            自定义
          </li>) : null}
        </ul>
        {
          this.state.isCustom ? this.renderCustomBody() : null
        }
      </div>
    )
  }

  render() {
    return (
      <div ref="root" className="dropdown time-slider" style={{ display: 'inline-block' }} ref="root">
        <strong onClick={this.toggle}>
          <i className="iconfont icon-clock"></i>

          {this.state.displayText}

          <i className="iconfont icon-btn-arrow">&#xe619;</i>
        </strong>
        {
          this.state.isOpen ? this.renderBody() : null
        }
      </div>
    )
  }
}

DateRangePickerEnhanced.defaultProps = {
  Scope: DateRangeStoreEnhanced
}
